package com.ggbz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ggbz.common.utils.JwtUtil;
import com.ggbz.entity.Users;
import com.ggbz.entity.dto.LoginRequest;
import com.ggbz.entity.dto.UserUpdateRequest;
import com.ggbz.entity.vo.LoginResponse;
import com.ggbz.entity.vo.UserVO;
import com.ggbz.mapper.UsersMapper;
import com.ggbz.service.UsersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 用户表，存储所有用户的基本信息 服务实现类
 * </p>
 *
 * @author ggbz
 * @since 2025-03-08
 */
@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements UsersService {

    @Autowired
    private UsersMapper usersMapper;

    @Override
    public void deleteUser(Long userId) {
        int deleted = usersMapper.deleteById(userId);
        if (deleted == 0) {
            throw new RuntimeException("用户不存在");
        }
    }
    @Override
    public Users getUserById(Long userId) {
        Users user = usersMapper.selectById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在"); // 建议自定义异常
        }
        return user;
    }
    @Override
    public void updateUser(Long userId, UserUpdateRequest request) {
        UpdateWrapper<Users> wrapper = new UpdateWrapper<>();
        wrapper.eq("user_id", userId)  // 数据库字段名
                .set("phone", request.getPhone())
                .set("email", request.getEmail());

        int updatedRows = usersMapper.update(null, wrapper);
        if (updatedRows == 0) {
            throw new RuntimeException("用户不存在");
        }
    }

    @Override
    public LoginResponse login(LoginRequest request) {
        // 1. 查询用户
        QueryWrapper<Users> wrapper = new QueryWrapper<>();
        wrapper.eq("username", request.getUsername());
        Users user = usersMapper.selectOne(wrapper);

        // 2. 校验用户
        if (user == null) {
            throw new RuntimeException("用户名不存在");
        }
        if (!user.getPassword().equals(request.getPassword())) { // 实际开发需加密验证
            throw new RuntimeException("密码错误");
        }

        // 3. 生成Token（示例使用伪代码）
        String token = JwtUtil.getJwtToken(user.getUserId().toString(),user.getUsername());

        return new LoginResponse(
                user.getUserId(),
                user.getUsername(),
                user.getRole(),
                token
        );


    }
}
